<template>
    <div>
        <el-breadcrumb class="app-breadcrumb" separator="/">
            <transition-group name="breadcrumb">
                <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
                    <span
                        v-if="item.redirect === 'noRedirect' || index == levelList.length - 1"
                        class="no-redirect"
                        >{{ t(item.meta.title) }}</span
                    >
                    <!-- @click.prevent函数会阻止触发dom的原始事件，而去执行特定的事件 -->
                    <a v-else @click.prevent="handleLink(item)">{{ t(item.meta.title) }}</a>
                </el-breadcrumb-item>
            </transition-group>
        </el-breadcrumb>
    </div>
</template>

<script setup name="Breadcrumb">
import { compile } from 'path-to-regexp'
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const route = useRoute()
const router = useRouter()

const levelList = ref(null)

watch(
    route,
    (_route) => {
        if (_route.path.startsWith('/redirect/')) {
            return
        }
        getBreadcrumb()
    },
    {
        immediate: true
    } // 立即以当前路由的值为触发条件
)
function pathCompile(path) {
    //解决面包屑点击报错问题
    const { params } = route
    const toPath = compile(path)
    return toPath(params)
}
function handleLink(item) {
    const { redirect, path } = item
    if (redirect) {
        router.push(redirect)
        return
    }
    router.push(pathCompile(path))
}
function isDashboard(route) {
    const name = route && route.name
    if (!name) {
        return false
    }
    return name.trim() === 'dashboard'
}

function getBreadcrumb() {
    //当前路由的所有嵌套路径片段的路由记录，过滤掉无meta信息的
    let matched = route.matched.filter((item) => item.meta && item.meta.title)
    const first = matched[0]

    if (!isDashboard(first)) {
        matched = [
            {
                path: '/dashboard',
                meta: {
                    title: 'route_mata_title.dashboard'
                }
            }
        ].concat(matched)
    }

    levelList.value = matched.filter(
        (item) => item.meta && item.meta.title && item.meta.breadcrumb !== false
    )
}
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
    display: inline-block;
    font-size: 14px;
    line-height: 50px;
    margin-left: 8px;

    .no-redirect {
        color: #97a8be;
        cursor: text;
    }
}
</style>
